<template>
  <el-dialog
    class="pick-dialog"
    title="下单"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="700px"
    top="30vh"
  >
    <div class="form-box" v-loading="loading">
      <el-form
        ref="ruleForm"
        :rules="rules"
        :model="ruleForm"
        label-width="auto"
      >
        <el-form-item label="回收时间">
          <span>{{ info.recycleTime }}</span>
        </el-form-item>
        <el-form-item label="商品编号">
          <span>{{ info.id }}</span>
        </el-form-item>
        <el-form-item label="游戏类型">
          <span>{{ info.gameName }}</span>
        </el-form-item>
        <el-form-item label="账号">
          <span>{{ info.accountNumber }}</span>
        </el-form-item>
        <el-form-item label="回收人">
          <span>{{ info.recyclerName }}</span>
        </el-form-item>
        <el-form-item label="销售渠道" prop="saleChannel">
          <el-select
            v-model="ruleForm.saleChannel"
            placeholder="请选择销售渠道"
            style="width: 250px"
            filterable
            @change="saleChannelChange"
          >
            <el-option
              v-for="(dict, index) in dict.type.sale_user"
              :key="dict.label"
              :label="dict.label"
              :value="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="网易使用状态"
          v-if="info.gameXINType == '网易'"
          prop="wyStatus"
        >
          <el-select
            v-model="ruleForm.wyStatus"
            placeholder="请选择网易使用状态"
            style="width: 250px"
            filterable
          >
            <el-option
              v-for="(dict, index) in gameStatus"
              :key="index"
              :label="dict.name"
              :value="dict.id + ''"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售人" prop="saleUserId">
          <el-select
            v-model="ruleForm.saleUserId"
            placeholder="请选择销售人"
            style="width: 250px"
            filterable
            @change="saleChange"
          >
            <el-option
              v-for="(dict, index) in allUsers"
              :key="index"
              :label="dict.nickName"
              :value="dict.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="换绑人" prop="changeUserId">
          <el-select v-model="ruleForm.changeUserId" placeholder="请选择换绑人" style="width:250px" filterable
            @change="huanbangChange">
            <el-option v-for="(dict, index) in allUsers" :key="index" :label="dict.nickName"
              :value="dict.userId"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="原价" prop="salePrice">
          <el-input-number
            v-model="ruleForm.salePrice"
            :precision="2"
            :step="0.1"
            :max="9999999999999"
            placeholder="请输入原价"
            @change="computePrice"
            :controls="false"
            text-align="left"
            style="width: 250px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="销售折扣" prop="saleDiscount">
          <el-input-number
            disabled
            v-model="ruleForm.saleDiscount"
            :precision="2"
            :step="0.1"
            :max="9999999999999"
            placeholder="请选择销售渠道"
            @change="computePrice"
            :controls="false"
            text-align="left"
            style="width: 250px"
          ></el-input-number>
        </el-form-item>
        <!-- <el-form-item label="成本价" prop="costAmount">
          <el-input-number v-model="ruleForm.costAmount" :precision="2" :step="0.1" :max="9999999999999"
            placeholder="请输入成本价" :controls="false" text-align="left" style="width:250px"></el-input-number>
        </el-form-item> -->
        <el-form-item label="优惠金额" prop="discountAmount">
          <el-input-number
            v-model="ruleForm.discountAmount"
            :precision="2"
            :step="0.1"
            :max="9999999999999"
            placeholder="请输入优惠金额"
            @change="computePrice"
            :controls="false"
            text-align="left"
            style="width: 250px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="实收金额" prop="zdPrice">
          <el-input-number
            v-model="ruleForm.zdPrice"
            :precision="2"
            :step="0.1"
            :max="9999999999999"
            placeholder="请输入实收金额"
            :controls="false"
            text-align="left"
            style="width: 250px"
          ></el-input-number>
        </el-form-item>

        <!-- <el-form-item label="供货是否支付" prop="supllypay">
          <el-select v-model="ruleForm.supllypay" placeholder="请选择是否支付" style="width:250px">
            <el-option v-for="dict in dict.type.ifpay" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="销售是否支付" prop="ifPay">
          <el-select
            v-model="ruleForm.ifPay"
            placeholder="请选择是否支付"
            style="width: 250px"
          >
            <el-option
              v-for="dict in dict.type.ifpay"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="换绑类型" prop="bindStatus">
          <el-select v-model="ruleForm.bindStatus" placeholder="请选择换绑类型">
            <el-option
              v-for="(item, index) in buyerList"
              :key="index"
              :label="item.dictLabel"
              :value="item.dictLabel"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="换绑手机号"
          prop="buyerPhone"
          v-if="ruleForm.bindStatus == '已换绑'"
        >
          <el-input
            style="width: 250px"
            v-model="ruleForm.buyerPhone"
            placeholder="请输入买家换绑手机号"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="换绑截图"
          prop="buyerImg"
          v-if="ruleForm.bindStatus == '已换绑'"
        >
          <div class="flex">
            <!-- <el-upload
              :action="uploadImgUrl"
              :file-list="buyerImgList"
              :show-file-list="true"
              list-type="picture-card"
              multiple
              :on-success="handleAvatarSuccess"
              :on-remove="handleAvatarRemove"
              :on-preview="handlePictureCardPreview"
            >
              <i class="el-icon-plus"></i>
            </el-upload> -->
            <el-upload
              :action="uploadImgUrl"
              :file-list="buyerImgList"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :multiple="true"
              :drag="true"
              :on-success="handleAvatarSuccess"
              :on-remove="handleAvatarRemove"
              :http-request="uploadImgs"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>

        <!-- <el-form-item label="相关图片">
          <el-upload
            :action="uploadImgUrl"
            :file-list="step3Imgs"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :multiple="true"
            :drag="true"
            :on-success="handleUploadSuccessStep3"
            :on-remove="handleRemoveStep3"
            :http-request="uploadImgs"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item> -->
        <el-form-item label="备注" prop="remake">
          <el-input
            style="width: 500px"
            type="textarea"
            :rows="5"
            v-model="ruleForm.remake"
            placeholder="请输入备注"
            maxlength="600"
            :show-word-limit="true"
          />
        </el-form-item>

        <div class="center">
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
        </div>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
// import customerServiceApi from "@/api/pickUp/customerService.js";
import ImageCompressor from "image-compressor.js";
import { postUpload } from "@/api/upload";
import { addRec } from "@/api/order/rec";
import supplyConfigApi from "@/api/system/supplyConfig";
import { getDicts } from "@/api/system/dict/data";
export default {
  name: "pick",
  dicts: ["sale_user", "ifpay"],
  data() {
    return {
      uploadImgUrl: "",
      dialogVisible: false,
      info: "",
      ruleForm: {
        saleChannel: null,
        salePrice: null,
        suplyprice: null,
        account: null,
        supllypay: null,
        ifPay: null,
        remake: null,
        saleid: null,
        saleDiscount: null,
        wyStatus: null,
        bindStatus: null,
        buyerPhone: null,
        buyerImg: null,
      },
      buyerList: [],
      step3Imgs: [], //图片列表
      loading: false,
      flag: false,
      B2CData: {},
      allUsers: [],
      rules: {
        bindStatus: [
          { required: true, message: "请选择换绑状态", trigger: "change" },
        ],
        buyerPhone: [
          { required: true, message: "请输入换绑手机号", trigger: "change" },
        ],
        buyerImg: [
          { required: true, message: "请上传换绑图片", trigger: "blur" },
        ],
        saleChannel: [
          { required: true, message: "请选择销售渠道", trigger: "change" },
        ],
        wyStatus: [
          { required: true, message: "请选择网易使用状态", trigger: "change" },
        ],
      },
      gameStatus: [
        { name: "已空闲", id: 2 },
        { name: "已售未换绑", id: 4 },
      ],
      buyerImgList: [],
    };
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  methods: {
    async getbuyerInfo() {
      const res = await getDicts("bindOrderRec");
      this.buyerList = res.data;
      console.log("res", res);
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    handleAvatarRemove(response, file, fileList) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      this.buyerImgList.forEach(function (element, key) {
        if (element.url === filePath) {
          that.buyerImgList.splice(key, 1); //新上传的图片
        }
      });
    },
    handleAvatarSuccess(e, file, fileList) {
      console.log("fileList", fileList);
      // 取得新上传的文件
      this.buyerImgList = fileList.filter((t) => {
        return t.url.indexOf("blob:") > -1;
      });
    },
    open(info, flag, data) {
      this.getAllUserList();
      this.getbuyerInfo();
      this.flag = flag;
      this.B2CData = data;
      this.info = info;
      console.log(info);
      this.ruleForm = {
        saleChannel: info.buyName || null,
        salePrice: info.newPrice || undefined,
        suplyprice: info.price || null,
        account: info.accountNumber || "",
        costAmount: info.costPrice || "",
        supllypay: "2",
        ifPay: "2",
        remake: null,
        wyStatus: null,
        bindStatus: null,
        buyerPhone: null,
        buyerImg: null,
      };
      this.dialogVisible = true;
      this.buyerImgList = [];
    },
    // 计算实收金额
    computePrice() {
      if (this.ruleForm.salePrice && this.ruleForm.saleDiscount) {
        this.ruleForm.zdPrice =
          ((this.ruleForm.salePrice - (this.ruleForm.discountAmount || 0)) *
            this.ruleForm.saleDiscount) /
          10;
      }
    },
    // 获取所有用户
    getAllUserList() {
      supplyConfigApi.getAllUserList().then((res) => {
        console.log("%c Line:104 🍯 所有用户res", "color:#93c0a4", res);
        this.allUsers = res.rows;
      });
    },
    // 销售渠道改变
    saleChannelChange(e) {
      let item = this.dict.type.sale_user[e];
      this.ruleForm.saleDiscount = item.value;
      this.ruleForm.saleChannel = item.label;
      console.log(
        "%c Line:153 🌽 this.dict.type.sale_user",
        "color:#465975",
        this.dict.type.sale_user
      );
      // 获取销售渠道原价
      let obj = {
        infoid: this.info.id,
        saleName: item.label,
      };
      supplyConfigApi.getPriceRec(obj).then((res) => {
        console.log("%c Line:148 🍯 res", "color:#ffdd4d", res);
        if (res.code == 200 && res.data && res.data.price) {
          this.ruleForm.salePrice = res.data.price;
        } else {
          this.ruleForm.salePrice = this.info.newPrice;
        }

        this.computePrice();
      });
    },
    // 销售人改变
    saleChange(e) {
      this.allUsers.forEach((r) => {
        if (r.userId == e) {
          this.ruleForm.saleUserName = r.nickName;
        }
      });
    },
    // 换绑人改变
    huanbangChange(e) {
      this.allUsers.forEach((r) => {
        if (r.userId == e) {
          this.ruleForm.changeUserName = r.nickName;
        }
      });
    },

    submitForm(formName) {
      if (this.step3Imgs && this.step3Imgs.length) {
        let newArr = [];
        this.step3Imgs.forEach((img) => {
          newArr.push({
            name: img.name,
            url: img.response.data.filePath,
          });
        });
        this.ruleForm.atta = JSON.stringify(newArr);
      } else {
        this.ruleForm.atta = "";
      }

      if (this.buyerImgList && this.buyerImgList.length) {
        let newArr = [];
        this.buyerImgList.forEach((img) => {
          newArr.push({
            name: img.name,
            url: img.response.data.filePath,
          });
        });
        this.ruleForm.buyerImg = JSON.stringify(newArr);
      } else {
        this.ruleForm.buyerImg = "";
      }
      // this.step3Imgs
      // console.log("%c Line:164 🍿 this.step3Imgs", "color:#3f7cff", this.step3Imgs);
      // return
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 处理财务相关图片
          this.loading = true;
          let orderRec = {};
          orderRec.saleChannel = this.ruleForm.saleChannel;
          orderRec.salechanelid = null;
          orderRec.salePrice = this.ruleForm.salePrice;
          orderRec.sumNum = this.info.thirdId;
          orderRec.games = this.info.gameName;
          orderRec.gameid = this.info.gameId;
          orderRec.ifPay = this.ruleForm.ifPay;
          orderRec.accountid = this.info.id;
          orderRec.account = this.ruleForm.account;
          orderRec.supllypay = this.ruleForm.supllypay;
          orderRec.suplyprice = this.ruleForm.suplyprice;
          orderRec.supllyId = this.info.createId;
          orderRec.remake = this.ruleForm.remake;
          orderRec.costAmount = this.ruleForm.costAmount;
          orderRec.discountAmount = this.ruleForm.discountAmount;
          orderRec.saleUserId = this.ruleForm.saleUserId;
          // orderRec.changeUserId = this.ruleForm.changeUserId;
          orderRec.saleUserName = this.ruleForm.saleUserName;
          // orderRec.changeUserName = this.ruleForm.changeUserName;
          orderRec.recyclerName = this.info.recyclerName;
          orderRec.saleDiscount = this.ruleForm.saleDiscount;
          orderRec.zdPrice = this.ruleForm.zdPrice;
          orderRec.atta = this.ruleForm.atta;
          orderRec.wyStatus = this.ruleForm.wyStatus;
          orderRec.bindStatus = this.ruleForm.bindStatus;
          orderRec.buyerPhone = this.ruleForm.buyerPhone;
          orderRec.buyerImg = this.ruleForm.buyerImg;
          addRec(orderRec).then((response) => {
            this.loading = false;
            this.$modal.msgSuccess("新增成功");
            this.dialogVisible = false;
            this.$parent.getList();
            if (this.flag) {
              this.B2CData.state = 4;
              this.$parent.editOrder(this.B2CData);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    // 第三步图片上传
    // 附件图片上传成功
    handleUploadSuccessStep3(res, file, fileList) {
      console.log("%c Line:1691 🥑 fileList", "color:#93c0a4", fileList);
      if (res.code == 200) {
        // 取得新上传的文件
        this.step3Imgs = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
        // this.step3Imgs
        console.log(
          "%c Line:225 🍩 this.step3Imgs",
          "color:#33a5ff",
          this.step3Imgs
        );
      }
    },
    // 附件图片删除
    handleRemoveStep3(response, fileList, file) {
      // console.log("%c Line:495 🍎 response", "color:#4fff4B", response);
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      this.step3Imgs.forEach(function (element, key) {
        if (element.url === filePath) {
          that.step3Imgs.splice(key, 1); //新上传的图片
        }
      });
    },
    // 压缩图片
    compressImage(file) {
      return new Promise((resolve, reject) => {
        new ImageCompressor(file.file, {
          quality: 0.6,
          checkOrientation: false,
          success(result) {
            resolve(result);
          },
          error(e) {
            reject();
          },
        });
      });
    },
    // 上传图片
    async uploadImgs(file) {
      // console.log("%c Line:466 🍆 压缩前file", "color:#2eafb0", file);
      // 获取压缩后的文件流
      let compreeBolb = await this.compressImage(file);
      // console.log("%c Line:468 🎂 压缩后compreeBolb", "color:#33a5ff", compreeBolb);
      const formData = new FormData();
      formData.append("file", compreeBolb); //压缩后的文件会自动转换成二进制文件流类型
      //上传图片到后台
      try {
        let uploadImg = await postUpload(formData);
        file.data = {
          filePath: uploadImg.msg,
        };
        file.code = 200;
        return file;
      } catch {
        file.code = 500;
        return file;
      }
    },
  },
};
</script>
<style scoped lang="css">
.center {
  text-align: center;
}

.pick-dialog >>> .el-dialog {
  margin-top: 100px !important;
}

.form-box {
  max-height: 600px;
  overflow-y: auto;
}
.pick-dialog >>> .el-upload-dragger {
  width: 150px;
  height: 150px;
  background-color: transparent;
  border: none;
}
</style>
